//
//  FFPayOrderChooseAddressView.m
//  FFMall
//
//  Created by ale tan on 2017/9/21.
//  Copyright © 2017年 IT.Bear. All rights reserved.
//

#import "FFPayOrderChooseAddressView.h"
#import "FFPayOrderAddressCell.h"
#import "FFPayOrderAddAddressView.h"

@interface FFPayOrderChooseAddressView ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataSources;
@property (nonatomic ,strong) FBAddressModel *selectedAddress;

@property (nonatomic ,strong) ChooseAddress chooseAddressBlock;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottom;

@end

@implementation FFPayOrderChooseAddressView

+ (instancetype)chooseAddressViewWithAddresses:(NSMutableArray *)addresses selectedAddress:(FBAddressModel *)selectedAddress{
    FFPayOrderChooseAddressView *orderView = [[[NSBundle mainBundle] loadNibNamed:@"FFPayOrderChooseAddressView" owner:nil options:nil] firstObject];
    orderView.dataSources = addresses;
    orderView.selectedAddress = selectedAddress;
    return orderView;
}

- (void)show{
    UIView *view = [UIApplication sharedApplication].keyWindow.rootViewController.view;//[[UIApplication sharedApplication].delegate window];
    self.frame = view.bounds;
    [self layoutIfNeeded];
    [view addSubview:self];
}

- (void)setChooseAddress:(ChooseAddress)chooseAddress{
    _chooseAddressBlock = chooseAddress;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    
    _toBottom.constant = isDeviceIphoneX?34:0;
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setTableFooterView];
}

- (void)setTableFooterView{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 44)];
//    footerView.backgroundColor = RGB_LIGHT_GRAY_COLOR;
    
    //标题
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 44)];
    label.text = @"新建地址";
    label.font = [UIFont systemFontOfSize:15];
    [footerView addSubview:label];
    
    //图标
    CGFloat iconWidth = 20;
    UIImageView *iconView = [[UIImageView alloc]initWithFrame:CGRectMake(IPHONE_WIDTH-iconWidth-14, (CGRectGetHeight(footerView.frame)-iconWidth)/2, iconWidth, iconWidth)];
    iconView.image = [UIImage imageNamed:@"addressAddIcon"];
    [footerView addSubview:iconView];
    
    footerView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addNewAddressWithModel:)];
    [footerView addGestureRecognizer:tap];
    
    _tableView.tableFooterView = footerView;
}

#pragma mark -UITableView-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSources.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [FFPayOrderAddressCell calculateForHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FFPayOrderAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FFPayOrderAddressCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"FFPayOrderAddressCell" owner:nil options:nil] firstObject];
    }
    
    FBAddressModel *model = _dataSources[indexPath.row];
    if ([model.addressId isEqual:_selectedAddress.addressId]) {
        [cell setSelected:YES];
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    else{
        [cell setSelected:NO];
    }
    [cell updateCellWithModel:model IndexPath:indexPath];
    
    WS(weakSelf);
    [cell setEditAddress:^{
        [weakSelf addNewAddressWithModel:model];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _selectedAddress = _dataSources[indexPath.row];
}

#pragma mark -Events-
- (IBAction)clickBackgroundToCancle:(id)sender {
    [self removeFromSuperview];
}

- (IBAction)clickToCancleChooseAddress:(UIButton *)sender {
    [self removeFromSuperview];
    if (_chooseAddressBlock) {
        _chooseAddressBlock(nil);
    }
}

- (IBAction)clickToConfirmAddress:(UIButton *)sender {
    if(!_selectedAddress){
        [FFTipsView showTips:@"请选择一个地址"];
        return;
    }
    [self removeFromSuperview];
    if (_chooseAddressBlock) {
        _chooseAddressBlock(_selectedAddress);
    }
}

- (void)addNewAddressWithModel:(FBAddressModel *)editAddress{
    FFPayOrderAddAddressView *addAddressView = [FFPayOrderAddAddressView addressView];
    
    if ([editAddress isKindOfClass:[FBAddressModel class]]) {
        addAddressView.address = editAddress;
    }
    
    self.hidden = YES;
    WS(weakSelf);
    [addAddressView setAddNewAddress:^(FBAddressModel *model) {
        self.hidden = NO;
        //修改的地址
        if ([editAddress isKindOfClass:[FBAddressModel class]]) {
            for (int i=0; i<weakSelf.dataSources.count; i++) {
                FBAddressModel *tmpModel = weakSelf.dataSources[i];
                if ([tmpModel.addressId isEqual:model.addressId]) {
                    [weakSelf.dataSources replaceObjectAtIndex:i withObject:model];
                    if ([weakSelf.selectedAddress.addressId isEqual:model.addressId]) {
                        weakSelf.selectedAddress = model;
                    }
                    [weakSelf.tableView reloadData];
                    break;
                }
            }
        }
        //新增的地址
        else{
            if (model) {
                if([model.isDefault integerValue]){
                    [weakSelf.dataSources insertObject:model atIndex:0];
                    weakSelf.selectedAddress = model;
                }
                else{
                    [weakSelf.dataSources addObject:model];
                }
                
                [weakSelf.tableView reloadData];
                if (!weakSelf.selectedAddress) {
                    weakSelf.selectedAddress = model;
                }
                
                [weakSelf.tableView reloadData];
            }
        }
    }];
    [addAddressView show];
}

@end
